<template>
  <div class="app-container">
    <el-row>
      <div class="item-header">
        个人资料
      </div>
      <el-col :md="12">
        <p>
          <span>用户ID:</span><span>{{userDetailData.userId}}</span>
        </p>
        <P>
          <span>年龄:</span><span>{{userDetailData.age}}</span>
        </P>
        <P>
          <span>出生日期:</span><span>{{doFormatDateTime(userDetailData.birthday)}}</span>
        </P>
        <P>
          <span>用户昵称:</span><span>{{userDetailData.nickName}}</span>
        </P>
        <P>
          <span>手机号:</span><span>{{userDetailData.userName}}</span>
        </P>
        <P>
          <span>微信昵称:</span><span>{{userDetailData.weChatName}}</span>
        </P>
        <P>
          <span>注册时间:</span><span>{{doFormatDateTime(userDetailData.createTime)}}</span>
        </P>
      </el-col>
      <el-col :md="12">
        <P>
          <span>生理周期:</span><span>{{userDetailData.physiologicalLength}}</span>
        </P>
        <P>
          <span>例假持续时间:</span><span>{{userDetailData.menstrualLength}}</span>
        </P>
        <P>
          <span>生理周期波动:</span><span>{{userDetailData.cycleFloatingDays}}</span>
        </P>
        <P>
          <span>备孕时长:</span>
          <span v-if="userDetailData.preparePregnancy == '0'">还未备孕</span>
          <span v-if="userDetailData.preparePregnancy == '1'">3个月以下</span>
          <span v-if="userDetailData.preparePregnancy == '2'">3个月-6个月</span>
          <span v-if="userDetailData.preparePregnancy == '3'">6个月-1年</span>
          <span v-if="userDetailData.preparePregnancy == '4'">1年-2年</span>
          <span v-if="userDetailData.preparePregnancy == '5'">2年以上</span>
        </P>
        <P>
          <span>有效监测次数:</span><span>{{userDetailData.detectionCount}}</span>
        </P>
        <P>
          <span>总检测数:</span><span>{{userDetailData.count}}</span>
        </P>
        <P>
          <span>总优孕数:</span><span>{{userDetailData.ovuolaTimeCount}}</span>
        </P>
        <P>
          <span>最近检测时间:</span><span>{{doFormatDateTime(userDetailData.detectionTime)}}</span>
        </P>
      </el-col>
      <el-col :md="24">
        <div class="item-header flex-between">
          标签
          <el-button
            size="small"
            type="text"
            @click="isEditor=!isEditor"
          >{{isEditor?"编辑标签":"取消编辑"}}</el-button>
        </div>

        <span
          v-for="(item,index) in userTag"
          :key="index"
        >
          <el-tag v-if="isEditor">{{item.labelName}}</el-tag>
          <el-tag
            closable
            v-if="!isEditor"
            @close="handleClose(item.labelId,item.labelName)"
          >{{item.labelName}}</el-tag>
        </span>

        <el-button
          class="el-tag"
          size="small"
          v-if="!isEditor"
          @click="openAddTagDialog()"
        >+</el-button>

      </el-col>

      <div class="item-header">
        周期统计
      </div>
      <el-col :md="24">
        <userDetailChart
          :id="'dayBar'"
          :data='option'
        ></userDetailChart>
      </el-col>
    </el-row>

    <el-dialog
      title="添加标签"
      :visible.sync="addTagDialog"
      width="20%"
      center
    >

      <el-autocomplete
        class="inline-input"
        v-model="userAddTagData.name"
        :fetch-suggestions="querySearch"
        placeholder="请输入标签"
        :trigger-on-focus="false"
        @select="handleSelect"
      ></el-autocomplete>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addTagDialog = false">取 消</el-button>
        <el-button
          type="primary"
          @click="postAddUserLabel()"
        >保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import userDetailChart from "@/components/EasyChart";
import {
  fetchUserDetail,
  fetchUserLabel,
  fetchAddUserLabel,
  fetchLabelList,
  fetchDeleteUserLabel
} from "@/api/table";
import { formatDateTime, getDays } from "@/utils/common";

export default {
  data() {
    return {
      userDetailData: {},
      option: null,
      userTag: [],
      addTagDialog: false,
      isEditor: true,
      labelAllList: [],
      userAddTagData: {
        name: "",
        labelId: ""
      }
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      this.getUserDetail();
      this.getUserLabel();
      this.getLabelList();
    },
    querySearch(queryString, cb) {
      var restaurants = this.labelAllList;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },

    handleSelect(item) {
      this.userAddTagData.labelId = item.id;
    },
    doFormatDateTime(data) {
      return data ? formatDateTime(data) : "";
    },
    formatTime(e) {
      if (e) {
        let time = "";
        time = format("yyyy-MM-dd hh:mm:ss", new Date(e));
        return time;
      } else {
        return "";
      }
    },
    openAddTagDialog() {
      this.addTagDialog = true;
      this.userAddTagData.name = "";
      this.userAddTagData.labelId = "";
    },
    handleClose(id, name) {
      this.$confirm("是否删除 <" + name + "> 标签", "确认信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "删除",
        cancelButtonText: "放弃"
      })
        .then(() => {
          this.postDeleteUserLabel(id);
        })
        .catch(action => {
          this.$message({
            type: "info",
            message: "放弃删除"
          });
        });
    },
    async postAddUserLabel() {
      const res = await fetchAddUserLabel({
        userId: this.$route.query.userId,
        labelId: this.userAddTagData.labelId
      });
      this.addTagDialog = false;
      this.getUserLabel();
      this.$message({
        message: "添加成功",
        type: "success"
      });
    },
    async postDeleteUserLabel(id) {
      await fetchDeleteUserLabel({
        userId: this.$route.query.userId,
        labelId: id
      });
      this.getUserLabel();
      this.$message({
        message: "删除成功",
        type: "success"
      });
    },
    async getUserLabel() {
      const res = await fetchUserLabel({
        userId: this.$route.query.userId
      });
      this.userTag = [];
      res.data.forEach(item => {
        const data = {};
        data.labelName = item.labelName;
        data.labelId = item.labelId;
        this.userTag.push(data);
      });
    },

    async getLabelList() {
      const res = await fetchLabelList();
      res.data.forEach(items => {
        items.childLabels.forEach(item => {
          const data = {};
          data.id = item.childLabelId;
          data.value = item.childLabelName;
          this.labelAllList.push(data);
        });
      });
    },
    async getUserDetail() {
      const detail = await fetchUserDetail({
        userId: this.$route.query.userId
      });
      this.userDetailData = detail.data;
      const cycle = detail.data.menstrualCycle;
      const ovuola = detail.data.menstruationHistory;
      //周期统计
      let cycleItems = cycle.split(",");
      let cycleDay = [];
      let cycleDaySeries = [];
      //例假统计
      let ovuolaItems = ovuola.split(",");
      let ovuolaDay = [];
      let ovuolaDaySeries = [];
      for (let i = 0; i < cycleItems.length; i++) {
        const time1 = cycleItems[i].split(":");
        const time2 =
          time1[0].substr(0, 4) +
          "-" +
          time1[0].substr(4, 2) +
          "-" +
          time1[0].substr(6, 2);
        const time3 =
          time1[1].substr(0, 4) +
          "-" +
          time1[1].substr(4, 2) +
          "-" +
          time1[1].substr(6, 2);
        let time4 = [];
        time4.push(time2);
        time4.push(time3);
        cycleDay.push(getDays(time4[0], time4[1]).split(",").length);
        cycleDaySeries.push(time4[0] + "~" + time4[1]);
      }
      for (let i = 0; i < ovuolaItems.length; i++) {
        const time1 = ovuolaItems[i].split(":");
        const time2 =
          time1[0].substr(0, 4) +
          "-" +
          time1[0].substr(4, 2) +
          "-" +
          time1[0].substr(6, 2);
        const time3 =
          time1[1].substr(0, 4) +
          "-" +
          time1[1].substr(4, 2) +
          "-" +
          time1[1].substr(6, 2);
        let time4 = [];
        time4.push(time2);
        time4.push(time3);
        ovuolaDay.push(getDays(time4[0], time4[1]).split(",").length);
        ovuolaDaySeries.push(time4[0] + "~" + time4[1]);
      }
      this.option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: ["周期天数", "例假天数"]
        },
        itemStyle: {
          label: {
            show: true,
            position: "top",
            formatter: "{b}\n{c}"
          }
        },
        dataZoom: [
          {
            id: "dataZoomX",
            type: "slider",
            xAxisIndex: [0],
            filterMode: "filter"
          },
          {
            id: "dataZoomY",
            type: "slider",
            yAxisIndex: [0],
            filterMode: "empty"
          }
        ],
        xAxis: {
          type: "category",
          data: cycleDaySeries
        },
        yAxis: [
          {
            type: "value",
            name: "天",
            position: "left",
            axisLine: {
              lineStyle: {
                color: "#999"
              }
            },
            axisLabel: {
              formatter: "{value}"
            }
          }
        ],
        series: [
          {
            name: "周期天数",
            type: "bar",
            data: cycleDay,
            itemStyle: {
              normal: { label: { show: true, position: "top", fontSize: 14 } }
            }
          },
          {
            name: "例假天数",
            type: "bar",
            data: ovuolaDay,
            itemStyle: {
              normal: { label: { show: true, position: "top", fontSize: 14 } }
            }
          }
        ]
      };
    }
  },
  components: {
    userDetailChart
  }
};
</script>
<style lang="less" scoped>
p {
  font-size: 16px;
  display: flex;
  span {
    flex: 1;
    color: #515a6e;
  }
  span:last-child {
    flex: 4;
    color: #999999;
  }
}
.el-tag {
  margin: 5px;
}
.item-header {
  margin: 0;
  line-height: 32px;
  font-weight: bold;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #eee;
}
.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

